package com.online.onlineshop.services.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.online.onlineshop.entity.Comment;
import com.online.onlineshop.entity.User;
import com.online.onlineshop.mapper.CommentMapper;
import com.online.onlineshop.mapper.UserMapper;
import com.online.onlineshop.services.ForCommentService;
import com.online.onlineshop.utils.ReturnCode;
import com.online.onlineshop.utils.ReturnData;
import com.online.onlineshop.vo.CommentParamVo;
import com.online.onlineshop.vo.CommentVo;
import com.online.onlineshop.vo.ProdCommentVO;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @author zihao.wang1
 * @date 2022/4/25
 */
@Service
public class ForCommentServiceImpl implements ForCommentService {

    @Resource
    CommentMapper commentMapper;
    @Resource
    UserMapper userMapper;

    @Override
    public Integer addComment(Comment comment, Integer uid, String username) {
        comment.setUid(uid);
        comment.setCreatedTime(new Date());
        comment.setCreatedUser(username);
        return commentMapper.insert(comment);
    }

    @Override
    public Comment selectComment(Integer oid, Integer pid) {
        QueryWrapper<Comment> wrapper = new QueryWrapper<>();
        wrapper.eq("oid", oid).eq("pid", pid);
        return commentMapper.selectOne(wrapper);
    }

    @Override
    public Integer updateComment(Comment comment, Integer uid, String userName) {
        comment.setModifiedTime(new Date());
        comment.setModifiedUser(userName);
        QueryWrapper<Comment> wrapper = new QueryWrapper<>();
        wrapper.eq("oid", comment.getOid()).eq("pid", comment.getPid());
        return commentMapper.update(comment, wrapper);
    }

    @Override
    public ReturnData<List<CommentVo>> selectByComment(Comment comment, int pageNum, int limit, int uid) {
        Page<CommentVo> page = new Page<>(pageNum, limit);
        CommentParamVo commentParamVo = new CommentParamVo();
        commentParamVo.setCreatedUser(comment.getCreatedUser());
        commentParamVo.setPid(comment.getPid());
        commentParamVo.setComment(comment.getComment());
        commentParamVo.setPageNum(pageNum);
        commentParamVo.setLimit(limit);
        User user = userMapper.selectById(uid);
        if (user.getUserType() == 1) {
            commentParamVo.setPuid(uid);
        }
        IPage<CommentVo> pg = commentMapper.commentPageList(page, commentParamVo);
        return new ReturnData<>(pg.getRecords(), pg.getTotal(), pg.getCurrent());
    }

    @Override
    public ReturnData<List<ProdCommentVO>> selectCommentByPid(Integer pid) {
        List<ProdCommentVO> voList = commentMapper.selectVoList(pid);
        return new ReturnData<>(ReturnCode.SUCCESS, voList);
    }
}
